package io.github.bw.tutorial

class RuleSpec extends Script {
  String name
  Closure<Boolean> when
  Closure<Boolean> _pass
  Closure<Boolean> reject
  Closure<Boolean> retrieve

  def name(String name) {
    this.name = name
  }

  void when(Closure<Boolean> closure) { this.when = closure }

  void reject(Closure<Boolean> closure) { this.reject = closure }

  void pass(Closure<Boolean> closure) { this._pass = closure }

  void retrieve(Closure<Boolean> closure) { this.retrieve = closure }

  def run() {
    boolean isReject = false
    if (when != null && !when.call()) {
      return isReject
    }
    if (reject != null) {
      isReject = reject.call()
    } else if (_pass != null) {
      isReject = !_pass()
    }

    if (isReject && retrieve != null) {
      isReject = !retrieve.call()
    }

    return isReject
  }
}

def rule(@DelegatesTo(strategy = Closure.DELEGATE_ONLY, value = RuleSpec) Closure cl) {
  def rule = new RuleSpec()
  def ruleClosure = cl.rehydrate(rule, this, this)
  ruleClosure.resolveStrategy = Closure.DELEGATE_ONLY
  ruleClosure.setProperty("age", 30)
  ruleClosure.setProperty("蚂蚁分", 799)
  ruleClosure.call()
  println rule.name + "\t 被拒绝：" +  rule.run()
}

rule {
  name '年龄拒绝'
  reject {
    age < 18 || age > 60
  }
}

rule {
  name '地域拒绝'
  // 这里只是列举地区，无其他含义
  reject_address = ["香港", "澳门", "台湾"]
  living_address = '香港'
  reject { living_address in reject_address }
}

rule {
  name = '通过规则'
  when { false }
  reject { 蚂蚁分 > 750 }
}